<?php
namespace app\mp\controller;

use app\admin\builder\ConfigBuilder;
use app\admin\builder\ListBuilder;
use app\admin\controller\MpAdmin;
use app\mp\model\MpMessage;
use app\mp\model\MpQrcode;
use app\mp\model\MpQrcodeStatistics;
use think\Config;
use think\Db;
use think\Request;
use think\Url;

class Admin extends MpAdmin
{
    public function msgDel($ids = null) {
        if($ids === null) {
            // 删除所有
            $result = Db::execute("delete from `".Config::get('database.prefix')."mp_message`");
        }else {
            $result = MpMessage::destroy($ids);
        }
        if($result){
            $this->success('删除成功',Url::build('msgList'));
        }else {
            $this->error('删除失败');
        }
    }
    /**
     * 留言列表
     * @param int $page
     */
    public function msgList($page = 1) {
        $totalCount = Db::name('MpMessage')->where(['mpid'=>get_selected_mp()['id']])->count('id');
        $listRows = 5;
        MpMessage::setApp($this->getApp());
        $data = MpMessage::all(function($query) use($page,$listRows){
            $query->page($page,$listRows)->where(['mpid'=>get_selected_mp()['id']])->order('create_time','desc');
        });



        $builder = new ListBuilder();
        return $builder
            ->title('留言列表')
            ->suggest('目前只支持文本留言')
            ->pagination($totalCount,$listRows)
            ->buttonDelete(Url::build('msgDel'))
            ->button('全部清空',['href'=>Url::build('msgDel'),'class'=>'ajax-post btn btn-danger'])
            ->keyUrlImage('headimgurl','头像')
            ->keyText('nickname','昵称')
            ->keyText('type','类型')
            ->keyText('content','内容')
            ->keyText('create_time','留言时间')
            ->data($data)
            ->fetch();
    }
    public function userList($page = 1)
    {
        $app = $this->getApp();
        $userList = $app->user->lists();
        $listRow = 8;


        $data = $app->user->batchGet(array_slice($userList['data']['openid'],$listRow * ($page - 1),$listRow))['user_info_list'];

        $builder = new ListBuilder();
        return $builder
            ->title('用户列表')
            ->keyUrlImage('headimgurl','头像')
            ->keyText('nickname','昵称')
            ->keyText('sex','性别',['男'=>1,'女'=>2])
            ->keyDoAction(urldecode(Url::build('userDetail',['openid'=>'###'])),'详情',false,'操作','openid')
            ->pagination($userList->total,$listRow)
            ->data($data)
            ->fetch();
    }
    public function userDetail($openid) {
        $app = $this->getApp();
        $data = $app->user->get($openid);
        foreach ($data as $key=>$val) {
            switch ($key) {
                case 'subscribe':
                    $val = $val==1?'已订阅':'未订阅';
                    break;
                case 'sex':
                    $val = $val==1?'男':'女';
                    break;
            }
        }

        $builder = new ConfigBuilder();
        return $builder
            ->title('用户详情')
            ->keyReadOnly('subscribe','是否订阅')
            ->keyReadOnly('openid','openid')
            ->keyReadOnly('nickname','昵称')
            ->keyReadOnly('sex','性别')
            ->keyReadOnly('language','语言')
            ->keyReadOnly('city','城市')
            ->keyReadOnly('province','省份')
            ->keyReadOnly('country','国家')
            ->data($data)
            ->buttonBack()
            ->fetch();
    }

    public function qrcodeList($page = 1) {
        $listRows = 1;
        $totalCount = Db::name('MpQrcode')->where(['mpid'=>$this->getMp()['id']])->count();
        MpQrcode::setApp($this->getApp());
        $data = MpQrcode::all(function ($query)use($page,$listRows){
            $query->where(['mpid'=>$this->getMp()['id']])->order('create_time desc')->page($page,$listRows);
        });

        $builder = new ListBuilder();
        return $builder
            ->title('场景二维码')
            ->buttonNew(Url::build('newTmpQrcode'),'创建临时二维码')
            ->buttonNew(Url::build('newForeverQrcode'),'创建永久二维码')
            ->buttonDelete(Url::build('delQrcode'))
            ->keyUrlImage('qrcode','二维码')
            ->keyText('scene_name','场景名')
            ->keyText('keyword','关键词')
            ->keyText('type','类型',[
                '临时二维码id'=>MpQrcode::TYPE_TMP_QRCODE_ID,
                '永久二维码id'=>MpQrcode::TYPE_FOREVER_QRCODE_ID,
                '永久二维码字符串'=>MpQrcode::TYPE_FOREVER_QRCODE_STR
            ])
            ->keyText('scene_id','场景id')
            ->keyText('scene_str','场景字符串')
            ->keyText('expire_date','过期日期')
            ->keyText('create_time','创建时间')
            ->keyText('state','状态')
            ->keyDoAction(urldecode(Url::build('newTmpQrcode',['id'=>'###'])),'编辑/详情',false)
            ->data($data)
            ->pagination($totalCount,$listRows)
            ->fetch();
    }
    public function qrcodeStatisticsDel($ids = null) {
        if($ids === null) {
            $result = Db::execute('delete from `'.Config::get('database.prefix').'mp_qrcode_statistics`');
        }else {
            $result = MpQrcodeStatistics::destroy($ids);
        }
        if($result){
            $this->success('删除成功');
        }else {
            $this->error('删除失败');
        }

    }
    public function qrcodeStatisticsList($page = 1) {
        MpQrcodeStatistics::setApp($this->getApp());
        $listRows = 5;
        $totalCount = Db::name('MpQrcodeStatistics')->where(['mpid'=>$this->getMp()['id']])->count();
        $data = MpQrcodeStatistics::all(function($query)use($page,$listRows){
            $query->where(['mpid'=>$this->getMp()['id']])->order('create_time desc')->page($page,$listRows);
        });
        $builder = new ListBuilder();
        return $builder
            ->title('扫码统计')
            ->buttonDelete('qrcodeStatisticsDel')
            ->button('全部清空',['href'=>Url::build('qrcodeStatisticsDel'),'class'=>'ajax-post btn btn-danger'])
            ->keyUrlImage('headimgurl','扫码者头像')
            ->keyText('nickname','扫码者昵称')
            ->keyText('scene_name','二维码场景名称')
            ->keyText('keyword','关联关键词')
            ->keyText('scene_type','扫码类型',[
                '临时二维码id'=>MpQrcode::TYPE_TMP_QRCODE_ID,
                '永久二维码id'=>MpQrcode::TYPE_FOREVER_QRCODE_ID,
                '永久二维码字符串'=>MpQrcode::TYPE_FOREVER_QRCODE_STR
            ])
            ->keyText('scene_id','场景id')
            ->keyText('scene_str','场景字符串')
            ->keyText('create_time','扫码时间')
            ->pagination($totalCount,$listRows)
            ->data($data)
            ->fetch();
    }
    public function newTmpQrcode(Request $request,$id = null) {
        if($request->isPost()) {
            $sceneName = $request->param('scene_name');
            $sceneId = $request->param('scene_id');
            $keyword = $request->param('keyword');
            $expire = $request->param('expire');
            if($id === null) {
                // 创建
                if(MpQrcode::addTmpQrcode($this->getApp(),$this->getMp()['id'],$sceneName,$sceneId,$keyword,$expire)) {
                    $this->success('创建成功',Url::build('qrcodeList'));
                }else {
                    $this->error('创建失败');
                }
            }else {
                // 修改
                $qrcode = MpQrcode::get($id);
                $qrcode['scene_name'] = $sceneName;
                $qrcode['keyword'] = $keyword;
                if($qrcode->save()) {
                    $this->success('修改成功',Url::build('qrcodeList'));
                }else {
                    $this->error('修改失败');
                }
            }
        }else {
            $data = [];
            if($id!==null) {
                $data = MpQrcode::get($id);
            }
            $builder = new ConfigBuilder();
            $builder
                ->title('临时二维码')
                ->keyText('scene_name','场景名')
                ->keyText('keyword','关联关键词');

            if($id===null) {
                // 未创建
                $builder
                    ->keyText('scene_id','场景ID')
                    ->keyText('expire','二维码过期时间','单位:秒');
            }else {
                // 已创建
                $builder
                    ->keyReadOnly('scene_id','场景ID')
                    ->keyReadOnly('expire','二维码过期时间','单位:秒')
                    ->keyReadOnly('ticket','ticket')
                    ->keyReadOnly('url','url','二维码解析后的url')
                    ->keyReadOnly('short_url','short url','二维码解析后的url的短地址');
            }

            return $builder
                ->buttonSubmit()
                ->buttonBack()
                ->data($data)
                ->fetch();
        }
    }
    public function newForeverQrcode(Request $request,$id = null) {
        $typemap = [
            'id'=>MpQrcode::TYPE_FOREVER_QRCODE_ID,
            '字符串'=>MpQrcode::TYPE_FOREVER_QRCODE_STR
        ];
        if($request->isPost()) {
            $sceneName = $request->param('scene_name');
            $keyword = $request->param('keyword');
            $type = $request->param('type');
            $sceneId = $request->param('scene_id');
            $sceneStr = $request->param('scene_str');

            if($id === null) {
                // 创建
                switch ($type){
                    case MpQrcode::TYPE_FOREVER_QRCODE_ID:
                        $result = MpQrcode::addForeverQrcodeId($this->getApp(),$this->getMp()['id'],$sceneName,$sceneId,$keyword);
                        break;
                    case MpQrcode::TYPE_FOREVER_QRCODE_STR:
                        $result = MpQrcode::addForeverQrcodeStr($this->getApp(),$this->getMp()['id'],$sceneName,$sceneStr,$keyword);
                        break;
                }
                if($result){
                    $this->success('创建成功',Url::build('qrcodeList'));
                }else {
                    $this->error('创建失败');
                }
            }else {
                // 修改
                $qrcode = MpQrcode::get($id);
                $qrcode['scene_name'] = $sceneName;
                $qrcode['keyword'] = $keyword;
                if($qrcode->save()) {
                    $this->success('修改成功',Url::build('qrcodeList'));
                }else {
                    $this->error('修改失败');
                }
            }
        }else {
            $builder = new ConfigBuilder();
            $builder
                ->title('永久二维码')
                ->keyText('scene_name','场景名')
                ->keyText('keyword','关联关键词');
            if($id===null) {
                // 未创建
                $builder
                    ->keySelect('type','二维码类型',$typemap)
                    ->keyText('scene_id','场景ID','要跟二维码类型对应')
                    ->keyText('scene_str','场景字符串','要跟二维码类型对应');

            }else {
                // 已创建
                $builder
                    ->keyReadOnly('type','场景类型',$typemap)
                    ->keyReadOnly('scene_id','场景ID')
                    ->keyReadOnly('scene_str','场景字符串')
                    ->keyReadOnly('ticket','ticket')
                    ->keyReadOnly('url','url','二维码解析后的url')
                    ->keyReadOnly('short_url','short url','二维码解析后的url的短地址');
            }

            return $builder
                ->buttonSubmit()
                ->buttonBack()
                ->fetch();
        }

    }
    public function delQrcode($ids) {
        if(MpQrcode::destroy($ids)){
            $this->success('删除成功');
        }else {
            $this->error('删除失败');
        }
    }


}
